package com.gaotu.demo.mybatis;

import com.gaotu.demo.User;
import com.gaotu.demo.UserDao;
import com.gaotu.demo.mybatis.mapper.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;


@Component
public class SqlSessionTemplateBasedUserDao implements UserDao {

    @Autowired
    private SqlSessionTemplate sqlSessionTemplate;

    @Override
    public void insert(User user) {
        this.sqlSessionTemplate
                .insert("com.gaotu.demo.mybatis.mapper.UserMapper.insert", user);
    }
    @Override
    public User getById(Long id) {
        List<User> users =  this.sqlSessionTemplate
                .selectList("com.gaotu.demo.mybatis.mapper.UserMapper.selectByPrimaryKey",
                        id);
        return users.isEmpty() ? null : users.get(0);
    }

    @Override
    public void update(User user) {
        this.sqlSessionTemplate.
                update("com.gaotu.demo.mybatis.mapper.UserMapper.updateByPrimaryKey", user);
    }

    @Override
    public void deleteById(Long id) {
        this.sqlSessionTemplate
                .delete("com.gaotu.demo.mybatis.mapper.UserMapper.deleteByPrimaryKey", id);
    }


    @Override
    public User getByName(String name) {
        List<User> users =  this.sqlSessionTemplate
                .selectList("com.gaotu.demo.mybatis.mapper.UserMapper.selectByName", name);
        return users.isEmpty() ? null : users.get(0);
    }

}
